package com.bjx.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bjx.system.domain.entity.RoleMenuEntity;
import com.bjx.system.mapper.RoleMenuMapper;
import com.bjx.system.service.IMenuService;
import com.bjx.system.service.IRoleMenuService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @desc: 角色菜单关联服务实现
 * @author: liushuai
 * @date: 2022/10/14
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenuEntity> implements IRoleMenuService {
    @Resource
    private RoleMenuMapper roleMenuMapper;
    @Resource
    private IMenuService menuService;


    @Override
    public List<String> listRoleMenuIdSon(Long roleId) {
        List<Long> pids = menuService.listPidAll();
        LambdaQueryWrapper<RoleMenuEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.select(RoleMenuEntity::getMenuId);
        wrapper.eq(RoleMenuEntity::getRoleId,roleId);
        List<RoleMenuEntity> roleMenuEntities = roleMenuMapper.selectList(wrapper);
        if(CollectionUtil.isEmpty(roleMenuEntities)){
            return Collections.emptyList();
        }
        List<String> menuIds = roleMenuEntities.stream().filter(res -> !pids.contains(res.getMenuId())).map(RoleMenuEntity::getMenuId).map(String::valueOf).collect(Collectors.toList());
        return menuIds;
    }

    @Override
    public void insertRoleMenuBatch(List<RoleMenuEntity> roleMenuEntities, Long roleId) {
        deleteRoleMenuByRoleId(roleId);
        if(CollectionUtil.isNotEmpty(roleMenuEntities)){
            roleMenuEntities.forEach(res->{
                res.setRoleId(roleId);
            });
            this.saveBatch(roleMenuEntities);
        }

    }

    @Override
    public void deleteRoleMenuByRoleId(Long roleId) {
        LambdaQueryWrapper<RoleMenuEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(RoleMenuEntity::getRoleId,roleId);
        roleMenuMapper.deleteById(roleId);
    }
}
